<template>
  <a-spin :loading="loading" tip="授权登录中...">
    <div class="container">
      <div class="login-layout">
        <div class="left-image">
          <img src="https://dyj-dc.oss-cn-beijing.aliyuncs.com/web/images/login_bg.png" alt="Login Background" />
        </div>
        <div class="right-content">
          <div class="company-logo">
            <img :src="companyLogo as string" alt="Company Logo" />
          </div>
          <div class="login-title">
            <h1>{{ projectNameEn }}</h1>
          </div>
          <!-- 扫码展示区 -->
          <div class="qr-code-area">
            <p class="qr-code-title">
              即将在
              <span>{{ loginBy ? '飞书' : '浏览器' }}</span>
              中打开{{ projectNameCn }}
            </p>
            <div class="login-content">
              <div class="auth-login" v-show="loginBy">
                <div class="auth-content">
                  <img class="auth-icon" :src="fsLogo" alt="" />
                  <span>•••</span>
                  <img class="auth-icon" :src="dcLogo" alt="" />
                </div>
                <a-button class="auth-btn" type="primary">授权登录</a-button>
              </div>
              <div v-show="!loginBy" id="qr-code-box"></div>
              <div v-show="!loginBy" class="qr-code-tip">请使用飞书扫描二维码登录</div>

              <div class="login-by">
                <a-popover :title="loginBy ? '飞书授权登录' : '飞书扫码登录'">
                  <img class="login-by-icon" :src="loginBy ? `${ossUrl}/web/images/qr_s.png` : fsLogo" alt="" @click="loginBy = !loginBy" />
                </a-popover>
              </div>
            </div>
          </div>

          <!-- 这里可以添加右侧内容 -->
          <!-- <LoginForm /> -->
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
import { useAppStore, useUserStore } from '@/store'
import Message from '@arco-design/web-vue/es/message'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const { companyLogo, ossUrl, fsApiId, projectNameEn, projectNameCn } = useAppStore()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

const fsLogo = 'https://dyj-dc.oss-cn-beijing.aliyuncs.com/web/images/fs_logo.png'
const dcLogo = 'https://dyj-dc.oss-cn-beijing.aliyuncs.com/web/images/fs_mode.png'
const loginBy = ref(false)
const loading = ref(false)
const clientId = fsApiId
const appId = fsApiId

// 重定向地址
const redirectUri = window.location.origin + '/login'
// 飞书登录对象
const goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&state=STATE`

onMounted(() => {
  // 判断是否有code
  if (route.query.code) {
    loading.value = true
    loginRequst(route.query.code)
    return
  }

  initFsQr()
})

// 初始化飞书登录二维码
const initFsQr = () => {
  // 不是飞书内部
  if (!(window as any).h5sdk) {
    const QRLoginObj = QRLogin({
      id: 'qr-code-box',
      goto: goto,
      width: '260',
      height: '260',
      style: 'border:none;',
    })

    var handleMessage = function (event: { origin: any; data: { tmp_code: any } }) {
      // 使用 matchOrigin 和 matchData 方法来判断 message 和来自的页面 url 是否合法
      if (QRLoginObj.matchOrigin(event.origin) && QRLoginObj.matchData(event.data)) {
        var loginTmpCode = event.data.tmp_code
        // 存一个暂时会话 将参数存起来 用于配置详情参数跳转
        sessionStorage.setItem('formula_audit', JSON.stringify(route.query))
        // 在授权页面地址上拼接上参数 tmp_code，并跳转
        window.location.href = `${goto}&tmp_code=${loginTmpCode}`
      }
    }
    if (typeof window.addEventListener != 'undefined') {
      window.addEventListener('message', handleMessage, false)
    } else if (typeof window?.attachEvent != 'undefined') {
      // window?.attachEvent('onmessage', handleMessage);
    }
    return
  }

  // 飞书内部【自动授权登录】
  loading.value = true
  ;(window as any).h5sdk.ready(async (res: any) => {
    tt.requestAuthCode({
      appId,
      // 获取成功后的回调
      async success({ code }: any) {
        loginRequst(code)
      },
      // 获取失败后的回调
      async fail(err: any) {
        const { errno, errMsg } = err
        console.log(err, '获取失败后的回调')
        if (!errno) return
        Message.error(errMsg)
      },
    })
  })
}
// 登录请求
const loginRequst = async (code: any) => {
  try {
    loading.value = true
    const query: any = {
      platform: 'dc',
      login_by: 'feishu',
      appid: appId,
      code,
    }

    // await userStore.login({ username: 'admin', password: 'admin' } as LoginData)
    await userStore.fslogin(query)
    Message.success('登录成功')
    // 登录成功后跳转
    const { redirect } = router.currentRoute.value.query
    await router.replace({
      name: (redirect as string) || 'Workplace',
      query: {},
    })

    // 确保页面完全加载后再关闭loading
    setTimeout(() => {
      loading.value = false
    }, 1000)
  } catch (err: any) {
    Message.error(err.message || '登录失败，请重试')
    console.error('登录失败:', err)
    loading.value = false
  }
}
</script>

<style lang="less" scoped>
:deep(.arco-spin-mask) {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  .login-layout {
    display: flex;
    height: 100%;
    width: 100%;
    overflow: hidden;
    .left-image {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .right-content {
      width: 40%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .company-logo {
        position: absolute;
        top: 20px;
        left: 20px;
        width: 260px;
        height: 42px;
        height: auto;
      }
      .login-title {
        position: absolute;
        left: 50%;
        top: 15%;
        transform: translateX(-50%) translateY(-15%);
        h1 {
          display: block;
          width: 100%;
          height: 67px;
          overflow-wrap: break-word;
          color: #636366;
          font-size: 36px;
          font-family: PingFangSC-Medium;
          font-weight: 500;
          white-space: nowrap;
          line-height: 67px;
          text-align: center;
        }
      }
      .login-content {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 45px;
        .auth-login {
          width: 100%;
          .auth-content {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            .auth-icon {
              display: block;
              width: 80px;
              height: 80px;
              border-radius: 8px;
              border: 1px solid rgba(0, 0, 0, 0.1);
            }
            span {
              padding: 0 32px;
              letter-spacing: 2px;
              text-align: center;
              display: inline-block;
              color: #646a73;
            }
          }
          .auth-btn {
            margin-top: 118px;
            display: inline-block;
            width: 72%;
            height: 52px;
            font-size: 20px;
            font-weight: 500;
            line-height: 28px;
            border-radius: 24px;
            margin-bottom: 32px;
          }
        }
        .login-by {
          .login-by-icon {
            width: 30px;
            height: 30px;
            cursor: pointer;
          }
        }
        .qr-code-tip {
          text-align: center;
          color: #898d90;
          font-size: 14px;
          margin-bottom: 12px;
        }
      }
      .qr-code-area {
        position: absolute;
        left: 50%;
        top: 70%;
        transform: translateX(-50%) translateY(-70%);
        text-align: center;
        width: 440px;
        height: 440px;
        border: 1px solid rgba(37, 57, 240, 0.1);
        border-radius: 4px;
        .qr-code-title {
          font-size: 14px;
          padding: 8px 0;
          display: flex;
          color: #ff860d;
          align-items: center;
          justify-content: center;
          background-color: #fff8f0;
          margin: 0;
          span {
            font-weight: 600;
            text-decoration: underline;
          }
        }
      }
    }
  }
}
</style>
